package com.ksr.logistics.service.impl;

import com.github.pagehelper.PageHelper;
import com.ksr.logistics.mapper.CustomerMapper;
import com.ksr.logistics.pojo.Customer;
import com.ksr.logistics.pojo.CustomerExample;
import com.ksr.logistics.pojo.User;
import com.ksr.logistics.service.CustomerService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<Customer> selPageCustomers(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10")Integer pageSize, String keyWord) {
        CustomerExample example = new CustomerExample();
        example.setOrderByClause("customer_id desc");
        CustomerExample.Criteria criteria = example.createCriteria();

        Subject subject= SecurityUtils.getSubject();
        User admin = (User) subject.getPrincipal();

        if ("业务员".equals(admin.getRolename())){
            criteria.andUserIdEqualTo(admin.getUserId());
        }
        if (StringUtils.isNotBlank(keyWord)){
            criteria.andCustomerNameLike("%"+keyWord+"%");
            CustomerExample.Criteria c2 = example.createCriteria();
            c2.andPhoneLike("%"+keyWord+"%");
            example.or(c2);
            CustomerExample.Criteria c3 = example.createCriteria();
            c3.andAddressLike("%"+keyWord+"%");
            example.or(c3);
        }
        PageHelper.startPage(page,pageSize);
        List<Customer> customers = customerMapper.selectByExample(example);
        return customers;
    }

    @Override
    public List<Customer> selCustomers() {
        CustomerExample example = new CustomerExample();
        return customerMapper.selectByExample(example);
    }

    @Override
    public int deleteById(Long id) {
        return customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(List<Long> ids) {
        int row=0;
        for (Long id:ids) {
            row+=customerMapper.deleteByPrimaryKey(id);
        }
        return row;
    }

    @Override
    public Customer selById(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }


    @Override
    public int insertCustomer(Customer customer) {
        return customerMapper.insert(customer);
    }

    @Override
    public int updateCustomer(Customer customer) {
        return customerMapper.updateByPrimaryKeySelective(customer);
    }

}
